package org.wangp.framework.db.config

import com.baomidou.mybatisplus.annotation.DbType
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusPropertiesCustomizer
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor
import org.apache.ibatis.logging.slf4j.Slf4jImpl
import org.apache.ibatis.reflection.MetaObject
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.boot.autoconfigure.AutoConfigureBefore
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import java.time.LocalDateTime

/**
 * @author wangpeng (๑•ᴗ•๑)
 * @date 2021/10/10 15:53
 */
@Configuration
@ConditionalOnClass(value = [MybatisPlusAutoConfiguration::class])
@AutoConfigureBefore(value = [MybatisPlusAutoConfiguration::class])
class MybatisPlusAutoConfig {

	companion object {
		const val CREATED_FILED_NAME = "created"
		const val EDITED_FILED_NAME = "edited"
		const val IS_DEL_FILED_NAME = "isDel"
		val log: Logger = LoggerFactory.getLogger(MybatisPlusAutoConfig::class.java)
	}

	/**
	 * 字段填充
	 */
	@Bean
	fun metaObjectHandler(): MetaObjectHandler {
		return object : MetaObjectHandler {
			override fun insertFill(metaObject: MetaObject) {
				strictInsertFill(metaObject, CREATED_FILED_NAME, LocalDateTime::class.java, LocalDateTime.now())
				strictInsertFill(metaObject, IS_DEL_FILED_NAME, Short::class.java, 0)
			}

			override fun updateFill(metaObject: MetaObject) {
				strictUpdateFill(metaObject, EDITED_FILED_NAME, LocalDateTime::class.java, LocalDateTime.now())
			}
		}
	}

	/**
	 * 分页插件
	 */
	@Bean
	fun mybatisPlusInterceptor() = MybatisPlusInterceptor().apply {
		addInnerInterceptor(PaginationInnerInterceptor(DbType.MYSQL))
	}

	@Bean
	fun mybatisPlusPropertiesCustomizer() = MybatisPlusPropertiesCustomizer {
		it.globalConfig.apply {
			isBanner = false
			dbConfig.apply {
				logicDeleteField = IS_DEL_FILED_NAME
				logicDeleteValue = "1"
				logicNotDeleteValue = "0"
			}
			try {
				superMapperClass = Class.forName("org.wangp.business.api.common.mapper.BaseMapper")
			} catch (e: Exception) {
			}
		}
		try {
			it.typeAliasesSuperType = Class.forName("org.wangp.business.api.domain.BaseDO")
		} catch (e: Exception) {
		}
	}

	@Bean
	fun configurationCustomizer() = ConfigurationCustomizer {
		it.logImpl = Slf4jImpl::class.java
	}
}
